/**
 * 性能优化工具
 * Story 3: Task 9 - 移动端性能优化
 */

/**
 * 图片懒加载Hook
 */
export const useLazyImage = () => {
  const [isIntersecting, setIsIntersecting] = React.useState(false)
  const imgRef = React.useRef<HTMLImageElement>(null)

  React.useEffect(() => {
    if (!imgRef.current) return

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsIntersecting(true)
          observer.disconnect()
        }
      },
      { rootMargin: '50px' }
    )

    observer.observe(imgRef.current)

    return () => observer.disconnect()
  }, [])

  return { imgRef, isIntersecting }
}

/**
 * 响应式图片组件Props
 */
interface ResponsiveImageProps {
  src: string
  alt: string
  mobileSrc?: string
  tabletSrc?: string
  className?: string
  lazy?: boolean
}

/**
 * 获取响应式图片源
 */
export const getResponsiveImageSrc = (
  src: string,
  mobileSrc?: string,
  tabletSrc?: string,
  breakpoint?: string
): string => {
  if (breakpoint === 'mobile' && mobileSrc) return mobileSrc
  if (breakpoint === 'tablet' && tabletSrc) return tabletSrc
  return src
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null

  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null
      func(...args)
    }

    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean = false

  return function executedFunction(...args: Parameters<T>) {
    if (!inThrottle) {
      func(...args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }
}

/**
 * 代码拆分 - 路由级别懒加载工具
 */
import React, { lazy, Suspense } from 'react'
import { Spin } from 'antd'

export const lazyLoadRoute = (importFunc: () => Promise<any>) => {
  const LazyComponent = lazy(importFunc)

  return (props: any) => (
    <Suspense fallback={<Spin spinning fullscreen />}>
      <LazyComponent {...props} />
    </Suspense>
  )
}

/**
 * 预加载关键资源
 */
export const preloadCriticalAssets = () => {
  // 预加载字体
  const fonts = [
    '/fonts/roboto-regular.woff2',
    '/fonts/roboto-bold.woff2'
  ]

  fonts.forEach(font => {
    const link = document.createElement('link')
    link.rel = 'preload'
    link.as = 'font'
    link.type = 'font/woff2'
    link.crossOrigin = 'anonymous'
    link.href = font
    document.head.appendChild(link)
  })
}

/**
 * 性能监控工具
 */
export const measurePerformance = {
  /**
   * 测量首屏加载时间
   */
  measureFCP: () => {
    if ('PerformanceObserver' in window) {
      const observer = new PerformanceObserver((list) => {
        for (const entry of list.getEntries()) {
          console.log('FCP:', entry.startTime, 'ms')
        }
      })
      observer.observe({ entryTypes: ['paint'] })
    }
  },

  /**
   * 测量页面切换时间
   */
  measureNavigation: (pageName: string, startTime: number) => {
    const endTime = performance.now()
    const duration = endTime - startTime
    console.log(`Navigation to ${pageName}:`, duration, 'ms')

    // 警告：超过100ms的页面切换
    if (duration > 100) {
      console.warn(`Slow navigation to ${pageName}: ${duration}ms`)
    }

    return duration
  },

  /**
   * 测量组件渲染时间
   */
  measureRender: (componentName: string, startTime: number) => {
    const endTime = performance.now()
    const duration = endTime - startTime
    console.log(`${componentName} render:`, duration, 'ms')
    return duration
  }
}

/**
 * 虚拟滚动配置
 */
export const virtualScrollConfig = {
  mobile: {
    itemHeight: 60,
    overscan: 3,
    threshold: 100 // 超过100项启用虚拟滚动
  },
  desktop: {
    itemHeight: 48,
    overscan: 5,
    threshold: 200
  }
}

/**
 * 检查是否需要虚拟滚动
 */
export const shouldUseVirtualScroll = (
  itemCount: number,
  isMobile: boolean
): boolean => {
  const threshold = isMobile
    ? virtualScrollConfig.mobile.threshold
    : virtualScrollConfig.desktop.threshold

  return itemCount > threshold
}

/**
 * 图片压缩质量建议
 */
export const imageQualitySettings = {
  mobile: {
    quality: 0.7,
    maxWidth: 750,
    format: 'webp'
  },
  tablet: {
    quality: 0.8,
    maxWidth: 1024,
    format: 'webp'
  },
  desktop: {
    quality: 0.85,
    maxWidth: 1920,
    format: 'webp'
  }
}

/**
 * Service Worker注册（用于离线缓存）
 */
export const registerServiceWorker = async () => {
  if ('serviceWorker' in navigator && process.env.NODE_ENV === 'production') {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js')
      console.log('Service Worker registered:', registration)
    } catch (error) {
      console.error('Service Worker registration failed:', error)
    }
  }
}

/**
 * 清理内存 - 移除不在视口的大型元素
 */
export const cleanupMemory = () => {
  // 清理过期的本地存储
  const storageKeys = Object.keys(localStorage)
  const now = Date.now()

  storageKeys.forEach(key => {
    if (key.startsWith('cache_')) {
      try {
        const item = JSON.parse(localStorage.getItem(key) || '{}')
        if (item.expiry && item.expiry < now) {
          localStorage.removeItem(key)
        }
      } catch (e) {
        // 忽略解析错误
      }
    }
  })
}

/**
 * 网络状态检测
 */
export const getNetworkStatus = () => {
  const connection = (navigator as any).connection ||
                    (navigator as any).mozConnection ||
                    (navigator as any).webkitConnection

  return {
    effectiveType: connection?.effectiveType || '4g',
    downlink: connection?.downlink || 10,
    rtt: connection?.rtt || 50,
    saveData: connection?.saveData || false
  }
}

/**
 * 根据网络状态调整资源加载策略
 */
export const shouldLoadHighQuality = (): boolean => {
  const network = getNetworkStatus()

  // 如果用户启用了数据节省模式，或网络慢，则加载低质量资源
  if (network.saveData || network.effectiveType === 'slow-2g' || network.effectiveType === '2g') {
    return false
  }

  return true
}
